package com.vanvalt.payhui.modules.pay.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.vanvalt.payhui.modules.pay.entity.Agent;
import com.vanvalt.payhui.modules.pay.service.AgentService;
import com.vanvalt.payhui.modules.pay.service.UserService;

/**
 * @author Xiaoyang
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/pay/agent")
public class AgentController extends BaseController {

	@Autowired
	private AgentService agentService;
	@Autowired
	private UserService userService;
	
	@ModelAttribute
	public Agent get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return agentService.get(id);
		}else{
			return new Agent();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(Agent agent, HttpServletRequest request, HttpServletResponse response, Model model) {

        Page<Agent> page = agentService.findPage(new Page<Agent>(request, response), agent); 
        model.addAttribute("page", page);
		return "modules/pay/agentList";
	}
	
	@RequestMapping(value = "form")
	public String form(Agent agent, Model model) {
		
		model.addAttribute("agent", agent);
		return "modules/pay/agentForm";
	}
	
	@RequestMapping(value = "save")
	public String save(Agent agent, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, agent)){
			return form(agent, model);
		}
		agentService.save(agent);
		
		if(agent.getId() == null || "".equals(agent.getId())){
			String status = agent.getStatus();
			if(status != null && "1".equals(status)){ // 通过审核
				User user = new User();
				
				
				userService.save(user);
			}
		}
		addMessage(redirectAttributes, "保存代理信息'" + StringUtils.abbr(agent.getRealName(),50) + "'成功");
		return "redirect:" + adminPath + "/pay/agent/?repage";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Agent agent, @RequestParam(required=false) Boolean isRe, RedirectAttributes redirectAttributes) {
		
		agentService.delete(agent);
		addMessage(redirectAttributes, (isRe!=null&&isRe?"发布":"删除")+"代理信息成功");
		return "redirect:" + adminPath + "/pay/agent/?repage";
	}
	
}
